package com.netx.ebs;
import javax.servlet.ServletConfig;
import com.netx.data.Connection;
import com.netx.generics.basic.Checker;


public abstract class AuthorizedServlet extends AuthenticatedServlet {

	private final String _permissionName;
	
	protected AuthorizedServlet(String permissionName) {
		this(new SecurityChecker[] {
			new ApplicationStateChecker(),
			new AuthenticationChecker(),
			new AuthorizationChecker(permissionName)
		}, permissionName);
	}
	
	// for AdministrationServlets:
	AuthorizedServlet(SecurityChecker[] checkers, String permissionName) {
		super(checkers);
		Checker.checkNull(permissionName, "permissionName");
		_permissionName = permissionName;
	}
	
	protected void ebsInit(ServletConfig config) throws Throwable {
		super.ebsInit(config);
		// Dont't check permissionName if the application hasn't been initialized
		// (the database might not be accessible)
		if(applicationInitialized()) {
			Connection c = getEbsContext().getDatabase().getConnection();
			Permission p = Entities.getPermissions(c).find(_permissionName);
			c.close();
			if(p == null) {
				addInitError("permission \""+_permissionName+"\" does not exist");
			}
		}
	}
}
